const config = {
	url: "",
	data: {},
}

let interceptorsRequest = (options) => options
let interceptorsResponseSuccess = (options) => options
let interceptorsResponseFail = (options) => options

const difineBaseConfig = (_config_) => {
	Object.assign(config, _config_)
}

const defineInterceptors = (op = {
	request,
	responseSuccess,
	responseFali,
}) => {
	interceptorsRequest = op.request;
	interceptorsResponseSuccess = op.responseSuccess;
	interceptorsResponseFail = op.responseFali;
}

const request = (options) => {
	let RequestTask;
	return new Promise((resole, reject) => {
		options = interceptorsRequest({
			...config,
			...options,
		});
		if (!options) return;
		config.data = config.data || {}
		options.data = options.data || {}
		RequestTask = uni.request({
			...options,
			url: config.url + options.url,
			data: {
				...config.data,
				...options.data,
			},
			success(res) {
				resole(interceptorsResponseSuccess(res))
			},
			fail(err) {
				// console.error(err);
				reject(interceptorsResponseFail(err))
			},
		})
		if (options.getTask) options.getTask(RequestTask)
		return RequestTask
	})
}


const post = (options) => request({
	...options,
	method: "POST",
})

const get = (options) => request({
	...options,
	method: "GET",
})

export default function useRequest() {
	return {
		difineBaseConfig,
		defineInterceptors,
		request,
		post,
		get,
	}
}